package sma.images.slides.client.slider;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.HasMouseOutHandlers;
import com.google.gwt.event.dom.client.HasMouseOverHandlers;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.FlowPanel;

public class ImgSlider extends FlowPanel implements HasMouseOverHandlers, HasMouseOutHandlers {

	private ISlidesCtrl imgSliderRepeatingCommand;
	private Scheduler imgSlideScheduler;
	private ControlsTable ftControls;
	private String [] imgPathAr;
	
	public ImgSlider(String width_, String height_, String ... imgPath_){
		super();
		imgPathAr = imgPath_;
		setSize(width_, height_);
		getElement().addClassName("imgSliderCls");
		
		initSliderImg();
		
		ftControls = new ControlsTable(imgSliderRepeatingCommand){

			@Override
			protected void onPlay() {
				imgSliderRepeatingCommand.play();
			}

			@Override
			protected void onPause() {
				imgSliderRepeatingCommand.pause();
			}

			@Override
			protected void onSlideSelected(int num_) {
				imgSliderRepeatingCommand.showSlide(num_);
			}
			
		};
		
		add(ftControls);
	}

	private void initImgSlideScheduler(){
		imgSlideScheduler = Scheduler.get();
		imgSliderRepeatingCommand = new ImgSliderRepeatingCommand(imgPathAr.length){

			@Override
			protected void showCurrent(int slideIndex_) {
				onShowCurrentSlide(slideIndex_);
			}
			
		};
		imgSlideScheduler.scheduleFixedPeriod((RepeatingCommand)imgSliderRepeatingCommand, 2500);
	}
	
	private void onShowCurrentSlide(int slideIndex_){
		ImgSlider.this.getElement().getStyle().setBackgroundImage("url('" + imgPathAr[slideIndex_] + "')");
		ftControls.selectNearNumbers(slideIndex_, false);
		ftControls.selectNumber(slideIndex_, true);
	}
	
	private void initSliderImg(){
		addMouseOverHandler(new MouseOverHandler() {
			
			@Override
			public void onMouseOver(MouseOverEvent event) {
				ftControls.setPlayPauseControlVisible(Visibility.VISIBLE);
			}
		});
		
		addMouseOutHandler(new MouseOutHandler() {
			
			@Override
			public void onMouseOut(MouseOutEvent event) {
				ftControls.setPlayPauseControlVisible(Visibility.HIDDEN);
			}
		});
		
		initImgSlideScheduler();
	}
	


	@Override
	public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) {
		return addDomHandler(handler, MouseOutEvent.getType());
	}

	@Override
	public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
		return addDomHandler(handler, MouseOverEvent.getType());
	}
}
